<extend name="Public/base"/>
<block name="style">

    <link rel="stylesheet" href="__STATIC__/styles/info_manage.css">
    <link rel="stylesheet" href="__STATIC__/styles/message.css">
    <link rel="stylesheet" href="__STATIC__/plugins/dropper/jquery.fs.dropper.min.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-table.css">
    <link rel="stylesheet" href="__STATIC__/styles/vendors/bootstrap-select.min.css">
    <style>
        table {table-layout:fixed;}
        .direct-chat-text{
            /*float: left;*/
            width:300px;
        }

        .direct-chat-text hr{
            border-top:1px solid black;
        }

        .right .direct-chat-text{
            float: right;
            margin-right: 0;
            background-color:#bfe49a;
        }
        .avatar{
            width:30px;
            height:30px;
        }
        .notice {
            width:15px;
            height:15px;
            line-height:10px;
            font-size:10px;
            color:#fff;
            text-align:center;
            background-color:#f00;
            border-radius:50%;
            position:absolute;
            right:20px;
            top:10px;
        }
        #parentpfx{
            text-align: center;
            color: #777;
            display: block;
            padding-top: 20px;
        }
    </style>
</block>
<block name="content">

    <div class="bs-example bs-example-tabs nav-tabs-custom"  data-example-id="togglable-tabs">
        <ul id="myTabs" class="nav nav-tabs" role="tablist">
            <li role="presentation" class="<eq name='showTab' value='1'>active</eq>"><a href="#home" id="home-tab" role="tab" data-toggle="tab" aria-controls="home" aria-expanded="true">信息管理</a></li>
            <li role="presentation" class="<eq name='showTab' value='2'>active</eq>"><a href="#profile" role="tab" id="profile-tab" data-toggle="tab" aria-controls="profile" aria-expanded="false">聊天</a></li>

        </ul>
        <div id="myTabContent" class="tab-content" >
            <div role="tabpanel" class="tab-pane fade <eq name='showTab' value='1'>active in</eq> container-fluid" id="home" aria-labelledby="home-tab">
                <div id="toolbar" >

                    <button id="remove" class="btn btn-danger btn-flat" disabled>
                        <i class="glyphicon glyphicon-remove"></i>删除
                    </button>


                    <div id="search" class="input-group input-group-sm col-md-9">
                        <span class="input-group-btn pull-right" style="margin-right: 40px">
                            <button id="searchBtn" type="button" class="btn btn-info btn-flat" >查询</button>
                        </span>
                        <input type="text" class="form-control pull-right" id="searchKeyword" style="margin-right: 10px;margin-left: 10px;">


                        <select class="selectpicker pull-right" id="selectionOption" style="margin-right: 10px">
                            <option value="1">标题</option>
                            <option value="2">发送人</option>
                            <option value="3">接收人</option>
                        </select>
                        <button id="searchAll" class="btn btn-info btn-flat pull-right" style="margin-right: 20px" >查看全部</button>

                    </div>
                    <div id="search-select" class="pull-right">

                    </div>
                    <!--<div class="col-md-3">-->

                    <!--</div>-->


                </div>

                <table id="table" data-toolbar="#toolbar">
                </table>

            </div>

            <div role="tabpanel"   class="tab-pane fade <eq name='showTab' value='2'>active in</eq>  content" id="profile" aria-labelledby="profile-tab">
                <div class="panel-body" >
                    <div class="col-md-2">
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control" id="searchUser">
                            <span class="input-group-btn">
                                <button id="searchUserBtn" type="button" class="btn btn-info btn-flat">搜索</button>
                            </span>
                        </div>
                        <div class="box box-solid">
                            <div class="box-header with-border">
                                <h3 class="box-title">联系人</h3>
                            </div>

                            <div class="box-body no-padding">
                                <ul class="nav nav-pills nav-stacked" id="userList" style="max-height: 473px; overflow-y: scroll">
                                    <!--<li class="active">-->
                                        <!--<a href="#"><img style="width: 30px;height: 30px;" src="__STATIC__/images/default_male.png" alt="">小红-->
                                        <!--<span class="notice"></span></a></li>-->
                                    <!--<li><a href="#"><i class="fa fa-envelope-o"></i> Sent</a></li>-->
                                    <!--<li><a href="#"><i class="fa fa-file-text-o"></i> Drafts</a></li>-->
                                    <!--<li><a href="#"><i class="fa fa-filter"></i> Junk <span class="label label-warning pull-right">65</span></a>-->
                                    <!--</li>-->
                                    <!--<li><a href="#"><i class="fa fa-trash-o"></i> Trash</a></li>-->
                                </ul>
                            </div>
                        </div>


                    </div>
                    <div class="col-md-10 message-im" style="display: none;height: 100%; ">
                        <div class="message-im-section" >
                            <div class="im-msg-title">
                                <strong class="realname">全家福</strong>
                                <input type="hidden" name="other_chat_id">
                            </div>
                            <div class="im-msg-list">
                                <div class="direct-chat-messages" style="height: 100%;">
                                    <div id="showMore" style="width: 100%;text-align: center">
                                        <p class="bg-success" id="showMoreBtn">查看更多</p>
                                    </div>
                                </div>
                            </div>
                            <div class="im-msg-form">
                                <div class="im-msg-textarea placeholder" id="im-msg-textarea" contenteditable="true"
                                     placeholder="在此输入消息..."></div>
                                <div class="im-msg-btn">

                                    <button type="button" class="btn btn-primary pull-right sendmsg">发送</button>
                                    <button type="button" class="btn btn-info pull-left sendImg">发送附件</button>
                                    <!--<a href="javascript:;" id="im-emoticon" class="im-emoticon"><i class="fa fa-smile-o"></i></a>-->
                                </div>
                            </div>
                        </div>

                    </div>

                </div>

            </div>
        </div>



    </div>


    <div class="modal fade" id="image_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2">
        <div class="modal-dialog" role="document">
            <form class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">发送附件</h4>
                </div>
                <div class="modal-body">

                    <div class="control-group row">
                        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 left">
                            <label class="control-label" ></label>
                        </div>
                        <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 right">
                            <div class="controls">
                                <div id="icon_div" class="col-sm-5" style="padding-left: 0px;">
                                    <input type="hidden" id="icon" name="icon" value="">

                                    <div class="image_show" style="display: none">

                                    </div>
                                    <div class="image_handle" data-toggle="tooltip" data-placement="top"
                                         title=""
                                         data-original-title="建议上传宽480px高320px的图片">
                                        <div class="dropped"></div>
                                    </div>
                                </div>
                                <div class="col-sm-5">
                                    <a href="javascript:void(0)" id="removeImg" class="btn btn-info invisible"
                                       role="button">删除</a>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 right">
                            <span id="parentpfx">附件发送支持：<br/>.jpg .png .gif .txt .doc 文件格式</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" style="display: none" class="btn btn-primary sendImgBtn">发送</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </form>
        </div>
    </div>


    <div class="modal fade" id="confirm_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">确认</h4>
                </div>
                <div class="modal-body">
                    删除该信息并不会从终端手机上删除。<br>
                    是否继续?
                </div>
                <div class="modal-footer">
                    <button type="button" id="confirmDelBtn" class="btn btn-danger btn-flat">删除</button>
                    <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="complex_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2"></div>
</block>

<block name="script">
    <script src="__STATIC__/scripts/vendors/bootstrap-select.min.js"></script>
    <script src="__STATIC__/scripts/vendors/bootstrap-table.js"></script>
    <script src="__STATIC__/plugins/dropper/jquery.fs.dropper.min.js"></script>
    <script src="__STATIC__/scripts/vendors/sortable-jquery.binding.js"></script>
    <script src="__STATIC__/scripts/vendors/Sortable.min.js"></script>
    <script>
        /**
         * Created by mingtao on 7/21/16.
         */

        var $table = $('#table');
        var $remove = $('#remove');
        var selections = [];
        var $imageModal = $('#image_modal');
        var $confirmModal = $('#confirm_modal');
        var tableHelper;
        var old_filename;
        var upload_filename;
        var file_size;
        var img_pre = "{:C('MESSAGE_IMG_URL')}";
        var showMore = $('#showMore');
        var user_id;


        var TableHelper = function(){
            var oTableHelper = new Object();

            oTableHelper.selections = [];


            oTableHelper.init = function(){
                $table.bootstrapTable({
                    formatLoadingMessage: function () {
                        return '正在努力地加载数据中，请稍候……';
                    },
                    formatRecordsPerPage: function (pageNumber) {
                        return '每页显示 ' + pageNumber + ' 条记录';
                    },
                    formatShowingRows: function (pageFrom, pageTo, totalRows) {
                        return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录，总共 ' + totalRows + ' 条记录';
                    },
                    formatSearch: function () {
                        return '搜索';
                    },
                    formatNoMatches: function () {
                        return '没有找到匹配的记录';
                    },
                    formatPaginationSwitch: function () {
                        return '隐藏/显示分页';
                    },
                    formatRefresh: function () {
                        return '刷新';
                    },
                    formatToggle: function () {
                        return '切换';
                    },
                    formatColumns: function () {
                        return '列';
                    },
                    responseHandler:function(res){
                        return res;
                    },
//                    height:getHeight(),
                    url:"{:U('infoList')}",
                    method:'get',
                    striped:true,
                    cache:false,
                    pagination:true,
                    sortable:true,
                    sortName:'send_time',
                    sortOrder:'desc',
                    sidePagination:'server',
                    queryParams:oTableHelper.queryParams,
                    pageNumber:1,
                    pageSize:10,
                    pageList:[10,20,50],
                    uniqueId:'message_id',
//                    search:true,
                   height:getHeight(),

                    columns:[
                        {
                            checkbox: true,
                            align: 'center'
                        },
                        {
                            field: 'title',
                            title: '标题',
                            align: 'center',
                            formatter: function (value) {
                                return '<a href="javascript: void 0" class="title">' + value + '</a>';
                            },
                            events: operateEvents
                        },
                        {
                            field: 'send_real_name',
                            title: '发送人',
                            formatter: function (value) {
                                if(value){
                                    return '<a href="javascript: void 0" class="send_user">' + value + '</a>';
                                }else{
                                    return '<a href="javascript: void 0" class="send_user">中心端</a>';
//                                    return '中心端';
                                }

                            },
                            events: operateEvents
                        },
                        {
                            field: 'receive_real_name',
                            title: '接收人',
                            editable: false,
                            align: 'center',
                            formatter: function (value) {
                                if(value){
                                    return '<a href="javascript: void 0" class="recv_user">' + value + '</a>';
                                }else{
//                                    return '中心端';
                                    return '<a href="javascript: void 0" class="recv_user">中心端</a>'
                                }

                            },
                            events: operateEvents
                        },
                        {
                            field: 'send_time',
                            title: '发送时间',
                            align: 'center',
                            sortable:true,
                        }
                    ]
                });


                $(window).resize(function () {
                    $table.bootstrapTable('resetView', {height:getHeight()});
                });



                $table.on('check.bs.table uncheck.bs.table ' +
                        'check-all.bs.table uncheck-all.bs.table', function () {
                    $('#remove').prop('disabled', !$table.bootstrapTable('getSelections').length);

                    // save your data, here just save the current page
                    oTableHelper.selections = oTableHelper.getIdSelections();
                    // push or splice the selections if you want to save all data selections
                });
            };

            oTableHelper.queryParams = function(params){
                var temp = {
                    limit:params.limit,
                    offset:params.offset,
                    rder:this.sortOrder,
                    search:$('#searchKeyword').val(),
                    searchOption:$('#selectionOption').val(),

                };
                return temp;
            };


            oTableHelper.getIdSelections = function(){
                return $.map($table.bootstrapTable('getSelections'), function (row) {
                    return row.message_id;
                })
            };

            oTableHelper.refresh = function(){
                $table.bootstrapTable('refresh');
            };

            return oTableHelper;
        };

        window.operateEvents = {
            'click .recv_user':function(e, value, row, index){
                // 中心端 == 0  selectionop  2 发  3 接
                if(row.receive_user_id > 0){
                    $('#searchKeyword').val(row.receive_real_name);
                }else{
                    $('#searchKeyword').val(-1);
                }
                $('#selectionOption').selectpicker('val',3);

                searchFunc();
            },
            'click .send_user':function(e, value, row, index){
                if(row.send_user_id > 0){
                    $('#searchKeyword').val(row.send_real_name);
                }else {
                    $('#searchKeyword').val(-1);
                }
                $('#selectionOption').selectpicker('val',2);
                searchFunc();
            },

            'click .title': function (e, value, row, index) {
                var from = row.send_real_name;
                var to = row.receive_real_name;
                var pre_url = "{:C('MESSAGE_IMG_URL')}";
                if(typeof (from)== undefined){
                    from = '中心端';
                }
                if(typeof(to) == undefined){
                    to = '中心端';
                }

                var enclosures = row.enclosures;
                var enc_html = "";
                var enc_local = "";
                var url;
                if(enclosures && enclosures.length >0){
                    enc_html += "<ul>";
                    for(var i in enclosures){
                        url = pre_url + enclosures[i]['enclosure_url'].substr(0,2) + '/' + enclosures[i]['enclosure_url'];
                        enc_html += "<li><a target='_blank' href='" + url + "'>"+ enclosures[i]['enclosure_formerly'] +"</a></li>";
                    }
                    enc_html += "</ul>";
                    enc_html = '<div><label>附件:</label><div class="info-content">'+enc_html+'</div></div>';
                }
                if(row.longitude && row.latitude){
                    var url = "{:U('map')}";
                    url = url + '?message_id='+ row.message_id;
                    var posImg = "__STATIC__/images/position.png";
                   
                    enc_local += '<a target="_blank" href="'+url+'"><img style="width: 16px" src="'+ posImg+'"/>'+ row.position + '</a>'
                }
                
                var html = '\
    <div class="modal-dialog" role="document">\
      <div class="modal-content">\
        <div class="modal-header">\
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\
          <h4 class="modal-title">信息详情</h4>\
        </div>\
        <div class="modal-body">\
          <div>\
            <label>\
              接收人:\
            </label>\
            <span>'+to+'</span>\
          </div>\
          <hr>\
          <div class="row">\
            <div class="col-lg-7 col-md-7 col-sm-7 col-xs-7">\
              <label>\
                发送人:\
              </label>\
              <span>'+from+'</span>\
            </div>\
            <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">\
              <label>\
                发送时间:\
              </label>\
              <span>'+row.send_time+'</span>\
            </div>\
          </div>\
          <hr>\
          <div>\
            <label>\
              内容:\
            </label>\
            <p class="info-content">'+row.content+'</p>\
          </div>\
          <hr>'+enc_html+'<br/>'+enc_local+'</div>\
        <div class="modal-footer">\
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>\
        </div>\
      </div>\
    </div>\
    ';
                $('#complex_modal').html(html);
                $('#complex_modal').modal('show');
            }
        };

        function getHeight() {
            return $("#right").height()-30;
        }

        function getIcon(icon){
            var basePath  = "{:C('USER_ICON_URL')}" ;
            return basePath + icon;
        }

        function getChatUsers(){
            $.get(
                "{:U('getChatList')}",
                function(data){
                    if(data.status == 1){
                        $('#userlist').empty();
                        var html = '';
//                        var root = '__ROOT__';
//                        imUsers = data.data;

                        for(var i in data.data){
                            var user = data.data[i];
                            imUsers[user.user_id] = user;
                            var imagesrc  = getIcon(user.icon);
                            var cl = '';
                            var _chat_id = chat_key_pre + user.user_id;
                            if(_chat_id == other_chat_id){
                                cl = 'active'
                            }
                            if(user.unread>0){
                                html += '<li class="'+cl+'"><a class="imUser" data-id="'+ user.user_id+'" data-chat-id="'+_chat_id+'"><img class="avatar" src="'+ imagesrc  + '" >'+user.real_name+'<span class="notice"></span></a></li>';
                            }else{
                                html += '<li class="'+cl+'"><a class="imUser" data-id="'+ user.user_id+'" data-chat-id="'+_chat_id+'"><img class="avatar" src="'+ imagesrc  + '" >'+user.real_name+'</a></li>';
                            }
                        }
                        $('#userList').html(html);
                    }else{
                        layer.msg(data.msg);
                    }
                }
            )
        }
        function nofind(){
            var img=event.srcElement;
            img.src="__STATIC__/images/onerror.png";
            img.onerror=null;
        }
        function initDropper(){
            $('#icon_div .dropped').dropper({
                postKey: "file",
                action: "{:U('File/uploadPicture')}",
                postData: {thumbSizes: '320x480', is_msg_img:1},
                label: "把文件拖拽到此处",
                maxSize: 8388608
            }).on("fileComplete.dropper", onFileComplete)
                    .on("fileError.dropper", onFileError);

            $('#removeImg').on("click",clearImageView );
        }

        function onFileComplete(e, file, response) {
            if(response.status == 0){
                layer.msg(response.info);
            }else{
                old_filename = response.filename;
                upload_filename = response.info;
                file_size = response.filesize;
                viewImageTointro(response.savepath + response.info);
            }
        }

        function onFileError(e, file, error) {
            error == 'Too large' ? layer.msg('文件过大') : layer.msg(error);
        }

        function viewImageTointro(image) {
            if (image) {
                var root = "{:C('MESSAGE_IMG_URL')}";
                var imagesrc = root + '/' + image;
                $("#icon_div").find(".dropper-input").val("");
                $("#icon_div").find(".image_handle").hide();
                $("#icon_div").find(".image_show").show();
                $("#icon").val(image);
                $("#icon_div").find(".image_show").html("<img id='icon_preview' onerror='nofind()' src='" + imagesrc + "' class='img-responsive' >");
                $("#removeImg").removeClass('invisible');
                $('.sendImgBtn').show();
            }
        }

        function clearImageView () {
            $("#icon").val("");
            $("#icon_div").find(".image_show").html("");
            $("#icon_div").find(".image_handle").show();
            $("#icon_div").find(".dropper-input").val("");
            $("#removeImg").addClass('invisible');
            $('.sendImgBtn').hide();
        }

        function isInIM(){
            return $('#profile').hasClass('active');
        }

        function searchFunc(){
            $table.bootstrapTable('destroy');
            tableHelper.init();
            var val = $('#searchKeyword').val();
            if(val == '-1'){
                $('#searchKeyword').val('中心端');
            }
            // tableHelper = new TableHelper();            
        }

        $(function () {
            initDropper();
            initIM();
            tableHelper = new TableHelper();
            tableHelper.init();

            getChatUsers();

            $('#searchBtn').click(function () {
                searchFunc();
            });

            $('#searchAll').click(function () {
                $('#searchKeyword').val('');
                $table.bootstrapTable('refresh');
            });

            // 输入
            $(document).on('focus.textarea', '.im-msg-textarea', function() {
                var $val = $.trim($(this).html());
                if (!$val && !$val.length) {
                    $(this).removeClass('placeholder');
                }
            });

            $(document).on('blur.textarea', '.im-msg-textarea', function() {
                var $val = $.trim($(this).html());
                if (!$val && !$val.length) {
                    $(this).addClass('placeholder');
                }
            });

            
            $('.sendmsg').click(function () {
                sendMsg();
            });

            $('.sendImg').click(function () {
                $imageModal.modal('show');
            });

            $remove.click(function () {
                $confirmModal.modal('show');
            });

            $('#confirmDelBtn').click(function () {
                $confirmModal.modal('hide');
                $.post({
                    url:"{:U('deleteMsg')}",
                    data:{
                        selectedIds : tableHelper.selections
                    },
                    success:function(data){
                        if(data.status == 1){
                            layer.msg('删除成功');
                            $table.bootstrapTable('refresh');
                        }else{
                            layer.msg('删除失败');
                        }
                    }
                })
            });

            $('#showMoreBtn').click(function () {
                $.ajax({
                    url:"{:U('getMessagePageByUserId')}",
                    data:{
                        user_id:user_id,
                        startCtime:current_ctime,
                        pageCount:page_count
                    },
                    success:function (data) {
                        if(data.status == 1){
                            for(var i in data.data){
                                var message = data.data[i];
                                addMsgObjHtml(message, message.send_time, message.send_user_id, false);
//                                addMsgHtml(message.content, message.send_time,message.send_user_id);
                                current_ctime = message.send_time;
                            }
                            if(data.data.length < page_count){
                                showMore.hide();
                            }else{
                                showMore.show();
                            }
                        }
                    }
                });
            });

            $('.sendImgBtn').click(function () {
                $.post({
                    url:"{:U('sendImgMessage')}",
                    data:{
                        receive_user_id:other_user_id,
                        filesize:file_size,
                        filename:old_filename,
                        img_path:upload_filename
                    },
                    success:function (data, status) {
                        if(data.status == 0){
                            layer.msg(data.msg);
                        }else{
                            $imageModal.modal('hide');
                            var mObj = new Object();
                            mObj.title = '附件';
                            mObj.content ='由中心端' + my_name + '发送';
                            mObj.enclosure = [data.data];
                            addMsgObjHtml(mObj,getNowFormatDate(), 0, true);
//                            addMsgHtml('附件列表：'+ old_filename, getNowFormatDate(), 0);
                            if(chatSocket && chatSocket.readyState == WebSocket.OPEN){
                                var msg = new Object();
                                msg.cmd = '2';
                                msg.too = other_chat_id;
                                msg.type = 1;
                                msg.body = new Object();
                                msg.body.msg = my_user_id;
                                msg.body.type = 1;
                                chatSocket.send(JSON.stringify(msg));
                            }else{
                                layer.msg('socket连接断开，刷新页面以重试');
                            }
                        }
                    }
                })
            });

            $imageModal.on('show.bs.modal',function () {
               clearImageView();
            });

            $(document).on('click','.imUser', function () {


                user_id = $(this).attr('data-id');
                $(this).find('span.notice').remove();
                var user = imUsers[user_id];
                other_user_id = $(this).attr('data-id');
                other_chat_id = chat_key_pre + other_user_id;
                $('.im-msg-title .realname').text(user.real_name);
                $('.im-msg-title input[name=other_chat_id]').val(user_id);
                $(".direct-chat-messages .direct-chat-msg").remove();
                $('.message-im').show();
                $('#userList li').removeClass('active');
                $(this).parent().addClass('active');

                $.ajax({
                    url:"{:U('getMessagePageByUserId')}",
                    data:{
                        user_id:user_id,
                        startCtime:0,
                        pageCount:page_count
                    },
                    success:function (data) {
                        if(data.status == 1){
                            for(var i in data.data){
                                var message = data.data[i];
                                addMsgObjHtml(message, message.send_time, message.send_user_id, false);
//                                addMsgHtml(message.content, message.send_time,message.send_user_id);
                                current_ctime = message.send_time;
                            }
                            if(data.data.length < page_count){
                                showMore.hide();
                            }else{
                                showMore.show();
                            }
                        }
                        var msgContainer = $('.im-msg-list .direct-chat-messages');
                        msgContainer.scrollTop(msgContainer[0].scrollHeight);
                    }
                });
            })
            
        })

    </script>
</block>

<block name="im_script">
    <script>
        var my_user_id = "{:session('user_auth.uid')}";
        var my_name = "{:session('user_auth.realname')}";
        var chatSocket;
        var chat_id = $('input[name=chat_id]').val();
        var other_chat_id;
        var other_user_id;
        var chat_key_pre = "{:C('IM_CHAT_KEY')}";
        var imUsers = new Object();
        var current_ctime = 0;
        var page_count = 10;


        function addMsgObjHtml(msgObj, time_send, send_user_id, is_new){
            var centerIcon = "{:C('CENTER_ICON_URL')}";

            html = '';
            var enclosure = '';
            if(msgObj.longitude && msgObj.latitude){
                var url = "{:U('map')}";
                url = url + '?message_id='+ msgObj.message_id;
                var posImg = "__STATIC__/images/position.png";
                enclosure += '<hr/>';
                enclosure += '<a target="_blank" href="'+url+'"><img style="width: 16px" src="'+ posImg+'"/>'+ msgObj.position + '</a>'
            }
            if(msgObj.enclosure){
                enclosure += '<hr/><ul>';
                for(var i in msgObj.enclosure){
                    enclosure += "<li><a href='" + img_pre + msgObj.enclosure[i]['enclosure_url'] + "' target='_blank'>"+ msgObj.enclosure[i]['enclosure_formerly'] +"</a></li>"
                }
                enclosure += '</ul>';
            }
            if(send_user_id == 0){

                html += '<div class="direct-chat-msg right"> ' +
                    '<div class="direct-chat-info clearfix"> ' +
                    '<span class="direct-chat-name pull-right"></span> ' +
                    '<span class="direct-chat-timestamp pull-right">'+ time_send +'</span> ' +
                    '</div> ' +
                    '<img class="direct-chat-img" src="'+centerIcon+'" alt="Message User Image"> ' +
                    '<div class="direct-chat-text"> ' + msgObj.title + '<hr/>' +
                    '<span>'+ msgObj.content+'</span> ' + enclosure +
                    '</div> ' +
                    '</div>';
            }else{
                var user = imUsers[send_user_id];
                var icon = getIcon(user.icon);
                if(user){
                    html+= '<div class="direct-chat-msg"> ' +
                        '<div class="direct-chat-info clearfix"> ' +
                        '<span class="direct-chat-name pull-left">'+ user.real_name+'</span> ' +
                        '<span class="direct-chat-timestamp">' + time_send + '</span> ' +
                        '</div> ' +
                        '<img class="direct-chat-img" src="' + icon +'"> ' +
                        '<div class="direct-chat-text">' + msgObj.title + '<hr/>' +
                        '<span>'+ msgObj.content+'</span> ' + enclosure +
                        '</div> ' +
                        '</div>';
                }

            }

            var msgContainer = $('.im-msg-list .direct-chat-messages');
            if(is_new){
//                showMore.after(html);
                msgContainer.append(html);
                msgContainer.scrollTop(msgContainer[0].scrollHeight);
            }else{
                showMore.after(html);
//                msgContainer.prepend(html);
            }
        }


        function addMsgHtml(chat_text, time_send, send_user_id){
            var centerIcon = "{:C('CENTER_ICON_URL')}";
            html = '';
            var title = '';
            if(send_user_id == 0){
                title = '来自中心端';
                html += '<div class="direct-chat-msg right"> ' +
                        '<div class="direct-chat-info clearfix"> ' +
                        '<span class="direct-chat-name pull-right"></span> ' +
                        '<span class="direct-chat-timestamp pull-right">'+ time_send +'</span> ' +
                        '</div> ' +
                        '<img class="direct-chat-img" src="'+centerIcon+'" alt="Message User Image"> ' +
                        '<div class="direct-chat-text"> ' + title + '<hr/>' +
                        '<span>'+ chat_text+'</span> ' +
                        '</div> ' +
                        '</div>';
            }else{
                var user = imUsers[send_user_id];
                var icon = getIcon(user.icon);
                if(user){
                    html+= '<div class="direct-chat-msg"> ' +
                            '<div class="direct-chat-info clearfix"> ' +
                            '<span class="direct-chat-name pull-left">'+ user.real_name+'</span> ' +
                            '<span class="direct-chat-timestamp">' + time_send + '</span> ' +
                            '</div> ' +
                            '<img class="direct-chat-img" src="' + icon +'"> ' +
                            '<div class="direct-chat-text">标题 <hr>' +
                            '<span>'+ chat_text+'</span> <hr>附件' +
                            '</div> ' +
                            '</div>';
                }

            }

            var msgContainer = $('.im-msg-list .direct-chat-messages');
            msgContainer.append(html);
            msgContainer.scrollTop(msgContainer[0].scrollHeight);

        }


        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
            return currentdate;
        }

        function sendMsg(){
            var msgTextArea = $('#im-msg-textarea').text();
            if(msgTextArea == ''){
                layer.msg('内容为空');
                return;
            }
            $.post(
                    {
                        url:"{:U('sendTextMessage')}",
                        data:{
                            receive_user_id:other_user_id,
                            content:msgTextArea,
                        },
                        success:function (data, status) {
                            if(data.status = 0){
                                layer.msg(data.msg);
                            }else{
                                var mObj = new Object();
                                mObj.title = '来自中心端';
                                mObj.content = msgTextArea;
                                addMsgObjHtml(mObj,getNowFormatDate(), 0, true);
//                                addMsgHtml(msgTextArea, getNowFormatDate(), 0);
                                $('#im-msg-textarea').empty();
                                if(chatSocket && chatSocket.readyState == WebSocket.OPEN){
                                    var msg = new Object();
                                    msg.cmd = '2';
                                    msg.too = other_chat_id;
                                    msg.type = 1;
                                    msg.body = new Object();
//                                    msg.body.msg = my_user_id;
                                    msg.body.type = 1;
                                    msg.body.msg = 0;
                                    chatSocket.send(JSON.stringify(msg));
                                }else{
                                    layer.msg('socket连接断开，刷新页面以重试');
                                }
                            }
                        }
                    }
            );

        }


        function initIM(){
            chatSocket = new WebSocket("ws://im-lin.moboa.thebdsoft.com:9511");
            chatSocket.onopen = function(event){
                var msg = new Object();
                msg.cmd = 0;
                msg.userid = chat_id;
                chatSocket.send(JSON.stringify(msg));
            };

            chatSocket.onmessage = function(event){
                var msg = JSON.parse(event.data);
                if(msg.cmd == 2){
                    if(msg.type == 1){
                        if(isInIM()){
                            var first = $('.imUser:first');
                            var current = $('.imUser[data-id='+msg.body.msg+']');
                            if(first.is(current)){
                            }else{
                                current.insertBefore(first);
                            }
                            if(msg.body.msg == other_user_id){
                                current.trigger('click');
                            }else{
                                current.find('span.notice').remove();
                                current.append('<span class="notice"></span>');
//                                getChatUsers();
                            }
                        }else{
                            $('.unread_li').show();
                        }

//
////                            if(msg.to == chat_id){
//                        if(other_chat_id == msg.from){
//                            $('.imUsers li > a[data-id='+ msg.from +']').trigger('click');
//                        }else{
//                            var userObj = $('.imUsers li > a[data-id='+ msg.from +']');
//                            var unreadObj = userObj.find('.im-body span.unread');
//                            var unread = parseInt(unreadObj.text()) + 1;
//                            unreadObj.removeClass('hide');
//                            unreadObj.text(unread);
//                            total_unread += unread;
//                            update_total_unread();
////                                $('#message-im-btn .total_unread').text(total_unread);
//                        }
//                            }
                    }
                }
                console.log(event.data);
            }

        }
    </script>
</block>
